//! # 简单构建器实现
//! 
//! 本模块提供了RustCloud框架的简单构建器实现，支持链式调用和灵活的组件配置。

use crate::config::*;
// use crate::framework::RustCloudFramework;
use crate::builder::traits::*;
use rustcloud_core::{ServiceResult, ServiceError};
// use rustcloud_registry::{ServiceRegistry, NacosRegistry, ConsulRegistry};
// use rustcloud_loadbalancer::{LoadBalancerStrategy, RoundRobinStrategy, RandomStrategy, WeightedRoundRobinStrategy};
// use rustcloud_circuit_breaker::CircuitBreaker;
// use rustcloud_metrics::{MetricsCollector, MemoryMetricsCollector};
use std::sync::Arc;
use std::collections::HashMap;

/// RustCloud框架简单构建器
/// 
/// 使用Builder模式来配置和构建RustCloud框架实例
/// 支持链式调用和灵活的组件配置
pub struct SimpleRustCloudBuilder {
    config: RustCloudConfig,
    registry: Option<Arc<dyn ServiceRegistry>>,
    load_balancer: Option<Arc<dyn LoadBalancerStrategy>>,
    circuit_breaker: Option<Arc<CircuitBreaker>>,
    metrics_collector: Option<Arc<dyn MetricsCollector>>,
    custom_components: HashMap<String, Box<dyn std::any::Any + Send + Sync>>,
}

impl SimpleRustCloudBuilder {
    /// 创建新的构建器实例
    pub fn new(service_name: &str) -> Self {
        let mut config = RustCloudConfig::default();
        config.service.name = service_name.to_string();
        
        Self {
            config,
            registry: None,
            load_balancer: None,
            circuit_breaker: None,
            metrics_collector: None,
            custom_components: HashMap::new(),
        }
    }

    /// 从配置文件创建构建器
    pub async fn from_config_file(path: &str) -> ServiceResult<Self> {
        let config = RustCloudConfig::from_file(path).await?;
        Ok(Self {
            config,
            registry: None,
            load_balancer: None,
            circuit_breaker: None,
            metrics_collector: None,
            custom_components: HashMap::new(),
        })
    }

    /// 从配置对象创建构建器
    pub fn from_config(config: RustCloudConfig) -> Self {
        Self {
            config,
            registry: None,
            load_balancer: None,
            circuit_breaker: None,
            metrics_collector: None,
            custom_components: HashMap::new(),
        }
    }

    /// 解析注册中心URL
    fn parse_registry_url(&self, url: &str) -> Option<(String, String)> {
        if let Some(pos) = url.find("://") {
            let registry_type = url[..pos].to_string();
            let endpoint = url[pos + 3..].to_string();
            Some((registry_type, endpoint))
        } else {
            None
        }
    }

    /// 创建注册中心实例
    async fn create_registry(&self) -> ServiceResult<Arc<dyn ServiceRegistry>> {
        let registry_config = &self.config.components.registry;
        
        match registry_config.registry_type.as_str() {
            "nacos" => {
                let registry = NacosRegistry::new(
                    registry_config.endpoints.clone(),
                    registry_config.namespace.clone(),
                    registry_config.group.clone(),
                ).await?;
                Ok(Arc::new(registry))
            },
            "consul" => {
                let registry = ConsulRegistry::new(registry_config.endpoints.clone()).await?;
                Ok(Arc::new(registry))
            },
            "memory" | _ => {
                // 默认使用内存注册中心
                let registry = rustcloud_registry::MemoryRegistry::new();
                Ok(Arc::new(registry))
            }
        }
    }

    /// 创建负载均衡器实例
    fn create_load_balancer(&self) -> ServiceResult<Arc<dyn LoadBalancerStrategy>> {
        let lb_config = &self.config.components.load_balancer;
        
        match lb_config.strategy.as_str() {
            "round_robin" => Ok(Arc::new(RoundRobinStrategy::new())),
            "random" => Ok(Arc::new(RandomStrategy::new())),
            "weighted_round_robin" => {
                let strategy = WeightedRoundRobinStrategy::new(lb_config.weights.clone());
                Ok(Arc::new(strategy))
            },
            "least_connections" => {
                // TODO: 实现最少连接数策略
                Ok(Arc::new(RoundRobinStrategy::new()))
            },
            "consistent_hash" => {
                // TODO: 实现一致性哈希策略
                Ok(Arc::new(RoundRobinStrategy::new()))
            },
            _ => Err(ServiceError::ConfigError(format!(
                "不支持的负载均衡策略: {}", lb_config.strategy
            ))),
        }
    }

    /// 创建熔断器实例
    fn create_circuit_breaker(&self) -> ServiceResult<Option<Arc<CircuitBreaker>>> {
        let cb_config = &self.config.components.circuit_breaker;
        
        if !cb_config.enabled {
            return Ok(None);
        }

        let circuit_breaker = CircuitBreaker::new(
            cb_config.failure_threshold,
            cb_config.success_threshold,
            std::time::Duration::from_millis(cb_config.timeout_ms),
        );
        
        Ok(Some(Arc::new(circuit_breaker)))
    }

    /// 创建指标收集器实例
    async fn create_metrics_collector(&self) -> ServiceResult<Option<Arc<dyn MetricsCollector>>> {
        let metrics_config = &self.config.monitoring.metrics;
        
        if !metrics_config.enabled {
            return Ok(None);
        }

        let collector = MemoryMetricsCollector::new();
        Ok(Some(Arc::new(collector)))
    }
}

#[async_trait::async_trait]
impl RustCloudBuilderTrait for SimpleRustCloudBuilder {
    /// 构建RustCloud框架实例
    async fn build(&self) -> ServiceResult<RustCloudFramework> {
        // 验证配置
        self.config.validate()?;

        // 创建注册中心实例
        let registry = if let Some(registry) = &self.registry {
            registry.clone()
        } else {
            self.create_registry().await?
        };

        // 创建负载均衡器实例
        let load_balancer = if let Some(lb) = &self.load_balancer {
            lb.clone()
        } else {
            self.create_load_balancer()?
        };

        // 创建熔断器实例
        let circuit_breaker = if let Some(cb) = &self.circuit_breaker {
            Some(cb.clone())
        } else if self.config.components.circuit_breaker.enabled {
            self.create_circuit_breaker()?
        } else {
            None
        };

        // 创建指标收集器实例
        let metrics_collector = if let Some(collector) = &self.metrics_collector {
            Some(collector.clone())
        } else if self.config.monitoring.metrics.enabled {
            self.create_metrics_collector().await?
        } else {
            None
        };

        // 创建框架实例
        RustCloudFramework::new(
            self.config.clone(),
            registry,
            load_balancer,
            circuit_breaker,
            metrics_collector,
            self.custom_components.clone(),
        ).await
    }
    
    /// 获取配置
    fn get_config(&self) -> &RustCloudConfig {
        &self.config
    }
    
    /// 设置服务配置
    fn with_service_config(&mut self, config: ServiceConfig) -> &mut Self {
        self.config.service = config;
        self
    }
    
    /// 设置服务版本
    fn with_version(&mut self, version: &str) -> &mut Self {
        self.config.service.version = version.to_string();
        self
    }
    
    /// 设置运行环境
    fn with_environment(&mut self, env: &str) -> &mut Self {
        self.config.service.environment = env.to_string();
        self
    }
    
    /// 设置服务端口
    fn with_port(&mut self, port: u16) -> &mut Self {
        self.config.network.port = port;
        self
    }
    
    /// 添加服务标签
    fn with_tag(&mut self, key: &str, value: &str) -> &mut Self {
        self.config.service.tags.insert(key.to_string(), value.to_string());
        self
    }
    
    /// 设置注册中心
    fn with_registry(&mut self, registry_url: &str) -> &mut Self {
        // 解析注册中心URL并更新配置
        if let Some((registry_type, endpoint)) = self.parse_registry_url(registry_url) {
            self.config.components.registry.registry_type = registry_type;
            self.config.components.registry.endpoints = vec![endpoint];
        }
        self
    }
    
    /// 设置注册中心实例
    fn with_registry_instance(&mut self, registry: Arc<dyn ServiceRegistry>) -> &mut Self {
        self.registry = Some(registry);
        self
    }
    
    /// 设置Nacos注册中心
    fn with_nacos(&mut self, endpoints: Vec<String>, namespace: Option<String>) -> &mut Self {
        self.config.components.registry.registry_type = "nacos".to_string();
        self.config.components.registry.endpoints = endpoints;
        self.config.components.registry.namespace = namespace;
        self
    }
    
    /// 设置Consul注册中心
    fn with_consul(&mut self, endpoints: Vec<String>) -> &mut Self {
        self.config.components.registry.registry_type = "consul".to_string();
        self.config.components.registry.endpoints = endpoints;
        self
    }
    
    /// 设置负载均衡策略
    fn with_load_balancer(&mut self, strategy: &str) -> &mut Self {
        self.config.components.load_balancer.strategy = strategy.to_string();
        self
    }
    
    /// 设置负载均衡策略实例
    fn with_load_balancer_instance(&mut self, strategy: Arc<dyn LoadBalancerStrategy>) -> &mut Self {
        self.load_balancer = Some(strategy);
        self
    }
    
    /// 启用轮询负载均衡
    fn with_round_robin(&mut self) -> &mut Self {
        self.config.components.load_balancer.strategy = "round_robin".to_string();
        self
    }
    
    /// 启用随机负载均衡
    fn with_random(&mut self) -> &mut Self {
        self.config.components.load_balancer.strategy = "random".to_string();
        self
    }
    
    /// 启用加权轮询负载均衡
    fn with_weighted_round_robin(&mut self, weights: HashMap<String, u32>) -> &mut Self {
        self.config.components.load_balancer.strategy = "weighted_round_robin".to_string();
        self.config.components.load_balancer.weights = weights;
        self
    }
    
    /// 启用熔断器
    fn with_circuit_breaker(&mut self) -> &mut Self {
        self.config.components.circuit_breaker.enabled = true;
        self
    }
    
    /// 设置熔断器配置
    fn with_circuit_breaker_config(&mut self, config: CircuitBreakerConfig) -> &mut Self {
        self.config.components.circuit_breaker = config;
        self
    }
    
    /// 设置熔断器实例
    fn with_circuit_breaker_instance(&mut self, circuit_breaker: Arc<CircuitBreaker>) -> &mut Self {
        self.circuit_breaker = Some(circuit_breaker);
        self.config.components.circuit_breaker.enabled = true;
        self
    }
    
    /// 启用指标收集
    fn with_metrics(&mut self) -> &mut Self {
        self.config.monitoring.metrics.enabled = true;
        self
    }
    
    /// 设置指标配置
    fn with_metrics_config(&mut self, config: MetricsConfig) -> &mut Self {
        self.config.monitoring.metrics = config;
        self
    }
    
    /// 设置指标收集器实例
    fn with_metrics_collector(&mut self, collector: Arc<dyn MetricsCollector>) -> &mut Self {
        self.metrics_collector = Some(collector);
        self.config.monitoring.metrics.enabled = true;
        self
    }
    
    /// 启用Prometheus指标导出
    fn with_prometheus(&mut self, port: Option<u16>) -> &mut Self {
        self.config.monitoring.metrics.enabled = true;
        self.config.monitoring.metrics.prometheus.enabled = true;
        if let Some(port) = port {
            self.config.monitoring.metrics.port = port;
        }
        self
    }
    
    /// 启用分布式追踪
    fn with_tracing(&mut self) -> &mut Self {
        self.config.monitoring.tracing.enabled = true;
        self
    }
    
    /// 设置追踪配置
    fn with_tracing_config(&mut self, config: TracingConfig) -> &mut Self {
        self.config.monitoring.tracing = config;
        self
    }
    
    /// 设置Jaeger追踪
    fn with_jaeger(&mut self, endpoint: &str, service_name: Option<&str>) -> &mut Self {
        self.config.monitoring.tracing.enabled = true;
        self.config.monitoring.tracing.jaeger = Some(JaegerConfig {
            agent_endpoint: endpoint.to_string(),
            service_name: service_name.unwrap_or(&self.config.service.name).to_string(),
        });
        self
    }
    
    /// 设置日志配置
    fn with_logging_config(&mut self, config: LoggingConfig) -> &mut Self {
        self.config.monitoring.logging = config;
        self
    }
    
    /// 设置日志级别
    fn with_log_level(&mut self, level: &str) -> &mut Self {
        self.config.monitoring.logging.level = level.to_string();
        self
    }
    
    /// 启用网关
    fn with_gateway(&mut self, port: u16) -> &mut Self {
        self.config.components.gateway = Some(GatewayConfig {
            enabled: true,
            port,
            routes: Vec::new(),
            middleware: MiddlewareConfig {
                auth: None,
                rate_limit: None,
                cors: None,
            },
        });
        self
    }
    
    /// 设置网关配置
    fn with_gateway_config(&mut self, config: GatewayConfig) -> &mut Self {
        self.config.components.gateway = Some(config);
        self
    }
    
    /// 启用代理
    fn with_proxy(&mut self) -> &mut Self {
        self.config.components.proxy.enabled = true;
        self
    }
    
    /// 设置代理配置
    fn with_proxy_config(&mut self, config: ProxyConfig) -> &mut Self {
        self.config.components.proxy = config;
        self
    }
    
    /// 设置TLS配置
    fn with_tls(&mut self, cert_file: &str, key_file: &str, ca_file: Option<&str>) -> &mut Self {
        self.config.network.tls = Some(TlsConfig {
            enabled: true,
            cert_file: cert_file.to_string(),
            key_file: key_file.to_string(),
            ca_file: ca_file.map(|s| s.to_string()),
        });
        self
    }
    
    /// 设置性能配置
    fn with_performance_config(&mut self, config: PerformanceConfig) -> &mut Self {
        self.config.performance = config;
        self
    }
    
    /// 设置连接池配置
    fn with_connection_pool(&mut self, max_connections: u32, min_connections: u32) -> &mut Self {
        self.config.performance.connection_pool.max_connections = max_connections;
        self.config.performance.connection_pool.min_connections = min_connections;
        self
    }
    
    /// 设置线程池配置
    fn with_thread_pool(&mut self, core_threads: u32, max_threads: u32) -> &mut Self {
        self.config.performance.thread_pool.core_threads = core_threads;
        self.config.performance.thread_pool.max_threads = max_threads;
        self
    }
    
    /// 添加自定义组件
    fn with_custom_component<T: std::any::Any + Send + Sync>(
        &mut self,
        name: &str,
        component: T,
    ) -> &mut Self {
        self.custom_components.insert(name.to_string(), Box::new(component));
        self
    }
    
    /// 从环境变量合并配置
    fn merge_from_env(&mut self) -> ServiceResult<&mut Self> {
        self.config.merge_from_env()?;
        Ok(self)
    }
}